<?php
namespace app\index\controller;

use app\common\model\AttachMain;
use app\common\model\Cookie;
use app\common\model\PortalArticle;
use app\common\model\PortalShare;
use app\common\model\UserDownloadCount;
use app\common\model\UserDownloadLog;
use app\common\model\UserDownloadTimes;
use app\common\model\UserMain;
use app\common\model\Request as RequestBase;
use app\index\controller\Base;
use think\facade\App;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use think\Resource;
use think\response\Json;

class Index extends Base
{


    protected $hk_id;

    protected $isTry = false;

    protected $isWeek = false;

    protected $isDay = false;

    protected $hk_video_play = "https://asyn.huke88.com/video/video-play";

    protected $hk_source_download = "https://huke88.com/download/ajax-download-source-case";

    private function info_tpl($param = [])
    {
    }

    private function download_count()
    {
        global $_G;
        if (empty($_G['uid'])) {
            return [];
        }
        $result = [];
        foreach (UserDownloadCount::where('uid', '=', $_G['uid'])->select() as $data) {
            $result[$data['site_id']] = $data;
        }
        return $result;
    }

    public function index()
    {
        global $_G;

        if (isMobile()){
            if (!empty($_G['user'])){
                return $this->redirect_wap('/wap.html');
            }else{
                return $this->redirect_wap('/login.html');
            }
        }

        $vip = new UserMain();

        if (!empty($_G['user'])){
            $vip_type = $vip->getVipTypeTextAttr('', $_G['user']);

            if ($vip_type == '终身'){
                $_G['user']['vip_expire_time'] = '3000-01-01';
            }

            if (strtotime($_G['user']['vip_expire_time']) < time() && intval($_G['user']['vip_type']) !== -1){
                $isExpire = 1;
            }
        }else{
            return redirect('/index/account/login');
        }

        return View::assign([
            'vip_type' => $vip_type ?? '',
            'is_expire' => $isExpire ?? 0,
            'download_count' => $this->download_count(),
            'article_list'   => PortalArticle::where([['status', '=', 1]])->limit(5)->order('create_time', 'desc')->select(),
            'user_nav'       => $this->user_nav(),
        ])->fetch();
    }

    public function parse($id = '', $link = '')
    {
        global $_G;

        if (isMobile()){
            return $this->parseWap();
        }

        if (!Request::isPost() || !Request::isAjax()) {
            return redirect('index/index/index');
        }
        if (empty($link)) {
            return show_error('缺少素材解析地址');
        }
        if (empty($_G['uid'])) {
            return show_error('请先登陆后再使用此功能');
        }
        $last_log = UserDownloadLog::where('uid', '=', $_G['uid'])->order('log_id', 'desc')->find();
        if (!empty($_G['setting']['parse_space_time']) && intval($_G['setting']['parse_space_time']) > 0 && !empty($last_log)) {

            $has_time = intval($_G['setting']['parse_space_time']) - (intval(Request::time()) - $last_log->getData('create_time'));
            if ($has_time > 0) {
                return show_error('操作过于频繁，请 <strong class="text-danger">' . $has_time . '</strong> 秒后后再试');
            }
        }

        $startTime = strtotime(date('Y-m-d 00:00:01', time()));
        $endTime = strtotime(date('Y-m-d 23:59:59', time()));

        //校验用户权限

        $userInfo = $_G['user'];

        $res = $this->validateUser($userInfo);

        if ($res == -1){
            return show_error('您当天的可观看的次数已用尽！升级成为年卡或终身会员可无限观看');
        }

        if ($res == -2){
            return show_error('系统检测到您短时间内解析次数过多，请过段时间再试');
        }

        $vipExpireTime = $userInfo['vip_expire_time'];

        $freeTimes = $userInfo['free_times'];

        if ($userInfo['vip_type'] == -2 ){
            if ($freeTimes <= 0){ //检测是否有免费体验次数
                return show_error('您是非vip用户,请购买卡密进行充值');
            }else{
                $this->isTry = true;
            }
        }else{
            if (strtotime($vipExpireTime) < time() && intval($userInfo['vip_type']) !== -1){
                return show_error('您的vip已到期，请购买卡密进行充值');
            }
        }

        $this->hk_id = $id;

        $header   = [
            'Accept'  => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'Host'    => 'huke88.com',
        ];

        $baseRequest = new RequestBase($link, 'GET', '', $header,true,  1);

        $result = $baseRequest->send_request()->get_response_data();


        $is_source = false;
        $is_media = false;


        if (strpos($result, '相关下载') !== false){

            if (strpos($result, 'download-source-js') !== false){
                $is_source = true;
            }

            if (strpos($result, 'download-case-js') !== false){
                $is_media = true;
            }
        }

        preg_match('/<meta name="csrf-token" content="(.*?)">/', $result, $match);

        $csrf_token = $match[1];

        $postData = [
            'id' => $id,
            'exposure' => 1,
            'studySourceId' => 1,
            'confirm' => 0,
            'async' => 'false',
            '_csrf-frontend' => $csrf_token
        ];

        $videoGoHeader    = [
            'Accept'           => '*/*',
            'Content-Type'     => 'application/x-www-form-urlencoded; charset=UTF-8',
            'Content-Length'   => strlen(http_build_query($postData)),
            'Origin'           => 'https://huke88.com',
            'Referer'          =>$link,
        ];

        $videoPlayHttp = new  RequestBase(
            $this->hk_video_play,
            'POST',
            $postData,
            $videoGoHeader, true, 1);
        $res = $videoPlayHttp->send_request()->get_response_body();

        $rawResult = json_decode($res, true);

        if (empty($rawResult) || !isset($rawResult['app_id'])){

            push_wx_message($res);

            Cookie::where('id', '=', 1)->update([
                'error' => $res
            ]);

            return show_error('服务器解析错误，请稍后重试！若持续错误请联系客服');
        }

        $appId = $rawResult['app_id'];
        $tx_file_id = $rawResult['tx_file_id'];

        $lastPost['sign'] = $sign = $rawResult['sign'];
        $lastPost['t'] = $t = $rawResult['t'];
        $lastPost['us'] = $us=  $rawResult['us'];

        $getVideoUrl = "https://playvideo.qcloud.com/getplayinfo/v2/$appId/$tx_file_id?sign=$sign&t=$t&us=$us";


        $lastHeader = [
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'Host' => 'playvideo.qcloud.com',
            'Referer' => $link,
            'Origin' => 'https://huke88.com',
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'
        ];

        $lastHeader = new RequestBase($getVideoUrl, 'GET', "", $lastHeader,'',  1);

        $videoRes = $lastHeader->send_request()->get_response_body();

        $all = json_decode($videoRes, true);

        $m3u8Url = $all['videoInfo']['transcodeList'][1]['url'] ?? '';

        if ($is_source){
            $sourceUrl = $this->getDownloadSource($link, $csrf_token, 1);
        }

        if ($is_media){
            $mediaUrl = $this->getDownloadSource($link, $csrf_token, 2);
        }

        UserDownloadLog::create([
            'uid' => $_G['uid'],
            'parse_url' => $link,
            'create_time' => Request::time(),
            'create_ip' => Request::ip(),
        ]);


        if ($this->isDay || $this->isWeek){
            UserMain::where('uid', '=',  $_G['uid'])->update(['today_times' => $userInfo['today_times'] - 1]);
        }

        if ($this->isTry){
            UserMain::where('uid', '=',  $_G['uid'])->update(['free_times' => 0]);
        }

        return json([
            'code'      => 200,
            'info'      => $result['info'] ?? '',
            'source_url'     => $sourceUrl ?? '',
            'media_url' => $mediaUrl ?? '',
            'm3u8_url'      => $m3u8Url ?? '',
            'content'   => $result['content'] ?? '',
            'no_button' => $result['no_button'] ?? '',
        ]);
    }

    private function validateUser($user){

        $startTime = strtotime("-1 hour");
        $endTime = time();

        $parseCount = UserDownloadLog::where('uid', '=', $user['uid'])->whereBetweenTime('create_time', $startTime, $endTime)->order('log_id', 'desc')->count();

        if ($parseCount >= 7){
            return -2;
        }

        $vipType = intval($user['vip_type']);

        if ($vipType == 1 ){
            $this->isWeek = true;
        }

        if ($vipType == 0){
            $this->isDay = true;
        }

        if ($vipType == 0 || $vipType == 1){
            if (intval($user['today_times']) <= 0){
                return -1;
            }
        }

    }

    public function parseWap(){
        global $_G;

        $userInfo = $_G['user'];

        $vipExpireTime = $userInfo['vip_expire_time'];

        if (strtotime($vipExpireTime) < time() && intval($userInfo['vip_type']) !== -1){
            return Json::create(['code' => 500, 'msg' => '非VIP用户']);
        }

        $res = $this->validateUser($userInfo);

        if ($res == -1){
            return Json::create(['code' => 500, 'msg' => '您当天的可观看的次数已用尽！升级成为年卡或终身会员可无限观看']);
        }

        $id = Request::post('id');
        $link = Request::post('link');


        $this->hk_id = $id;

        $header   = [
            'Accept'  => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'Host'    => 'huke88.com',
        ];

        $baseRequest = new RequestBase($link, 'GET', '', $header,true,  1);

        $result = $baseRequest->send_request()->get_response_data();

        preg_match('/<meta name="csrf-token" content="(.*?)">/', $result, $match);

        $csrf_token = $match[1];

        $postData = [
            'id' => $id,
            'exposure' => 1,
            'studySourceId' => 1,
            'confirm' => 0,
            'async' => 'false',
            '_csrf-frontend' => $csrf_token
        ];

        $videoGoHeader    = [
            'Accept'           => '*/*',
            'Content-Type'     => 'application/x-www-form-urlencoded; charset=UTF-8',
            'Content-Length'   => strlen(http_build_query($postData)),
            'Origin'           => 'https://huke88.com',
            'Referer'          =>$link,
        ];

        $videoPlayHttp = new  RequestBase(
            $this->hk_video_play,
            'POST',
            $postData,
            $videoGoHeader, true, 1);
        $res = $videoPlayHttp->send_request()->get_response_body();

        $rawResult = json_decode($res, true);

        if (empty($rawResult) || !isset($rawResult['app_id'])){

            push_wx_message('wap解析:' . $res);

            Cookie::where('id', '=', 1)->update([
                'error' => $res
            ]);

            return show_error('服务器解析错误，请稍后重试！若持续错误请联系客服');
        }

        $appId = $rawResult['app_id'];
        $tx_file_id = $rawResult['tx_file_id'];

        $lastPost['sign'] = $sign = $rawResult['sign'];
        $lastPost['t'] = $t = $rawResult['t'];
        $lastPost['us'] = $us=  $rawResult['us'];

        $getVideoUrl = "https://playvideo.qcloud.com/getplayinfo/v2/$appId/$tx_file_id?sign=$sign&t=$t&us=$us";


        $lastHeader = [
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'Host' => 'playvideo.qcloud.com',
            'Referer' => $link,
            'Origin' => 'https://huke88.com',
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'
        ];

        $lastHeader = new RequestBase($getVideoUrl, 'GET', "", $lastHeader,'',  1);

        $videoRes = $lastHeader->send_request()->get_response_body();

        $all = json_decode($videoRes, true);

        $m3u8Url = $all['videoInfo']['transcodeList'][1]['url'] ?? '';


        return Json::create(['url' => $m3u8Url, 'code' => 200]);
    }


    private function getDownloadSource($link, $csrfToken, $type){

        $postData = [
            'id' => $this->hk_id,
            'type' => $type,
            'studySourceId' => 1,
            'confirm' => 1,
            '_csrf-frontend' => $csrfToken
        ];

        $header = [
            'Accept' => 'application/json, text/javascript, */*; q=0.01',
            'Content-Type'     => 'application/x-www-form-urlencoded; charset=UTF-8',
            'Content-Length'   => strlen(http_build_query($postData)),
            'Origin'           => 'https://huke88.com',
            'Referer'          =>$link,
        ];

        $videoPlayHttp = new  RequestBase(
            $this->hk_source_download,
            'POST',
            $postData,
            $header, true, 1);
        $res = $videoPlayHttp->send_request()->get_response_body();

        $sourceResult = json_decode($res, true);

        if (isset($sourceResult['download_url'])){
            return $sourceResult['download_url'];
        }

        return false;
    }


    public function searchWap(){
        global $_G;

        $userInfo = $_G['user'];

        $vipExpireTime = $userInfo['vip_expire_time'];

        if (strtotime($vipExpireTime) < time() && intval($userInfo['vip_type']) !== -1){
            return Json::create(['code' => 500, 'msg' => '非VIP用户']);
        }

        if ($userInfo['vip_type'] == -1){
            $expireTime = '永久有效';
        }else{
            $expireTime = $vipExpireTime;
        }

        return Json::create(['code' => 200, 'expireTime' => $expireTime]);
    }

    public function search($keywork = '')
    {
        $keywork = trim($keywork);
        if (Request::isPost()) {
            if (empty(Request::post('keywork/s'))) {
                return show_error('请输入关键字');
            }
            return redirect('index/index/search', ['keywork' => Request::post('keywork/s')]);
        }
        $search_list = !empty($keywork) ? PortalShare::where('status', '>', 0)->whereLike('subject', '%' . $keywork . '%')->paginate([
            'list_rows' => 32,
            'query'     => ['keywork' => $keywork],
        ]) : [];
        $page = !empty($search_list) ? $search_list->render() : '';
        return View::assign([
            'search_list' => $search_list,
            'page'        => $page,
            'keywork'     => $keywork,
        ])->fetch();
    }

    public function jump($download_url = '')
    {
        return View::assign(['download_url' => $download_url])->fetch();
    }

    public function redirect($download_url = '')
    {
        return View::assign(['download_url' => $download_url])->fetch();
    }

    public function redirect_wap($url){
        return redirect($url);
    }

    private function user_nav()
    {
        global $_G;
        $result = [
            [
                'name' => '个人中心',
                'icon' => 'icon-user',
                'url'  => url('index/user/index'),
            ],
        ];
       
//        if (!empty($_G['user']) && in_array($_G['user']['type'], ['system', 'proxy'])) {
//            $result[] = [
//                'name' => '商家代理',
//                'icon' => 'icon-users',
//                'url'  => url('index/user/proxy'),
//            ];
//        }
        $result[] = [
            'name' => '卡密充值',
            'icon' => 'icon-balance',
            'url'  => url('index/user/card'),
        ];

        $result[] = [
            'name' => '使用教程',
            'icon' => 'icon-gonggao',
            'url'  => "http://image.openows.com/%E8%A7%A3%E6%9E%90%E6%95%99%E7%A8%8B.gif",
        ];

        $result[] = [
            'name' => '卡密购买',
            'icon' => 'icon-weixinzhifu',
            'url'  => "http://faka.openows.com/",
        ];
        
        if (empty($_G['uid'])) {
            $result[] = [
                'name' => '用户登录',
                'icon' => 'icon-tuiguang',
                'url'  => url('index/account/login'),
            ];
            $result[] = [
                'name' => '注册账号',
                'icon' => 'icon-bangzhu',
                'url'  => url('index/account/register'),
            ];
        } else {
//			if ($_G['setting']['user_fission']) {
//			    $result[] = [
//			        'name' => '推广赚钱',
//			        'icon' => 'icon-tuiguang',
//			        'url'  => url('index/user/spread'),
//			    ];
//			}
            $result[] = [
                'name' => '修改密码',
                'icon' => 'icon-mima',
                'url'  => url('index/user/password'),
            ];
            $result[] = [
                'name' => '安全退出',
                'icon' => 'icon-logout',
                'url'  => url('index/account/logout'),
            ];
			
			
        }
        return $result;
    }

    public function code(){
        include_once __DIR__ . '/../../../extend/Tncode/TnCode.class.php';
        $tnCode =  new \TnCode();
        echo $tnCode->make();exit;
    }

    public function checkcode(){
        include_once __DIR__ . '/../../../extend/Tncode/TnCode.class.php';
        $tnCode =  new \TnCode();
        if ($tnCode->check()){
            echo "ok"; exit;
        }else{
            echo "error";exit;
        }
    }
}
